$(function(){
    goLogin();
    var _data = '',content=[],imageUrl=[],designerList=[],_id=[];

    var cartDesignerIds = localStorage.getItem('cartDesignerIds');
    console.log(cartDesignerIds)
    if(cartDesignerIds = 'null'){
        cartDesignerIds = null
    }
    var codeId = $.getUrlParam('orderId');
    var cartId = $.getUrlParam('cartId');
    
    if(codeId){
        console.log(codeId)
        getCodeData()
    }else{
        getInitData();
    }
    
    operationFn();
    submitFn();

    // FUN
    function getInitData(){
        post({
            url:'/customizeCart/designerList',
            data:{dsgIds:localStorage.getItem('dsgIds')},
            success:function(data){
                console.log(data);
                localStorage.setItem('_data',JSON.stringify(data));
                handleFirstMenu(data);
                // if(cartId){
                //     var oldData = {cartId:cartId}
                //     getOldData(oldData);
            // }else 
            // alert(localStorage.getItem('cartDesignerIds'))
                if(localStorage.getItem('cartDesignerIds')){
                    var oldData = {cartDesignerIds:localStorage.getItem('cartDesignerIds')}
                    getOldData(oldData);
                }
            }
        })
    };

    function getCodeData(){
        post({
            url:'/customizeOrder/designerList',
            data:{code:codeId},
            success:function(data){
                console.log(data);
                var dsgIds = [];
                for(var i=0; i<data.length; i++){
                    dsgIds.push(data[i]["id"])
                };
                console.log(dsgIds.toString())
                localStorage.setItem('dsgIds',dsgIds.toString())
                handleFirstMenu(data);
                post({
                    url:'/customizeOrder/findDesigner',
                    data:{code:codeId},
                    success:function(data){
                        console.log(data);
                        for(var i=0; i<data.length; i++){
                            _id.push(data[i]["id"]);
                            if(data[i]['imageUrl']){
                                $('.mainPic_'+data[i]["designerSpecGroup"]["id"]).attr('src',SERVER_CONTEXT_PATH+'/load/picture/'+data[i]['imageUrl'])
                            }else{
                                $('.mainPic_'+data[i]["designerSpecGroup"]["id"]).attr('src','../img/kong.png')
                            };
                            $('.textContain_'+data[i]["designerSpecGroup"]["id"]).val(data[i]["content"])
                        }
                    }
                })
            }
        })
    }

    function getOldData(oldData){
        post({
            url: '/customizeCart/findDesigner',
            data:oldData,
            success:function(data){
                console.log(data)
                for(var i=0; i<data.length; i++){
                    _id.push(data[i]["id"]);
                    if(data[i]['imageUrl']){
                        $('.mainPic_'+data[i]["designerSpecGroup"]["id"]).attr('src',SERVER_CONTEXT_PATH+'/load/picture/'+data[i]['imageUrl'])
                    }else{
                        $('.mainPic_'+data[i]["designerSpecGroup"]["id"]).attr('src','../img/kong.png')
                    };
                    $('.textContain_'+data[i]["designerSpecGroup"]["id"]).val(data[i]["content"])
                    
                }
            }
        })
    }

    function handleFirstMenu(data){
        for(var i = 0; i<data.length; i++){
            $('.menuList').append(
                '<div data-key="'+i+'">'+data[i]['name']+'</div>'
            );
            $('article').append(
                '<section class="tab contain_'+i+'">'
                    +'<img class="mainPic_'+data[i]['id']+'" src="../img/kong.png" alt="">'
                 +'</section>'
                
            );
            handleSecondMenu(i,data[i])
            choosePicFn(data[i])
        };
        $('.menuList>div').eq(0).addClass('menuList_action');
        $('section').eq(0).removeClass('tab');
    };

    function handleSecondMenu(key,data){
        console.log($('.contain_'+key+'>.itemList'))
        switch (data['designContent']['name']) {
            case "PICANDCHAR":
                $('.contain_'+key).append(
                    '<div class="itemList">'
                        +'<span data-itemlistid="'+data['id']+'" class="itemHeader_gm itemList_action">通用模板</span>'
                        +'<span data-itemlistid="'+data['id']+'" class="itemHeader_st">上传图片</span>'
                        +'<span data-itemlistid="'+data['id']+'" class="itemHeader_tw">添加文字</span>'
                    +'</div>'
                    +'<aside class="itemContain_gm_'+data['id']+'"></aside>'
                    +'<aside class="itemContain_st_'+data['id']+' tab">'
                        +'<input data-uppicid="'+data['id']+'" class="upPic" type="file"/>'
                        +'<img src="../img/shangchaun.png" alt="">'
                    +'</aside>'
                    +'<aside class="itemContain_tw_'+data['id']+' tab">'
                        +'<textarea maxlength="100" class="textContain_'+data['id']+'" placeholder="输入设计中需要的文字(100字内)"></textarea>'
                    +'</aside>'
                )
                break;
                
            case "CHARACTER":
                $('.contain_'+key).append(
                    '<div class="itemList">'
                        +'<span data-itemlistid="'+data['id']+'" class="itemHeader_tw itemList_action">添加文字</span>'
                    +'</div>'
                    +'<aside class="itemContain_tw_'+data['id']+'">'
                        +'<textarea maxlength="100" class="textContain_'+data['id']+'" placeholder="输入设计中需要的文字(100字内)"></textarea>'
                    +'</aside>'
                )
                break;
        
            case "PICTURE":
                $('.contain_'+key).append(
                    '<div class="itemList">'
                        +'<span data-itemlistid="'+data['id']+'" class="itemHeader_gm itemList_action">通用模板</span>'
                        +'<span data-itemlistid="'+data['id']+'" class="itemHeader_st">上传图片</span>'
                    +'</div>'
                    +'<aside class="itemContain_gm_'+data['id']+'"></aside>'
                    +'<aside class="itemContain_st_'+data['id']+' tab">'
                        +'<input data-uppicid="'+data['id']+'" class="upPic" type="file"/>'
                        +'<img src="../img/shangchaun.png" alt="">'
                    +'</aside>'
                )
                break;
        
            default:
                break;
        }
    }

    function choosePicFn(data){
        console.log(data)
        if(data["pictureList"]){
            for(var j = 0; j<data["pictureList"].length; j++){
                $('.itemContain_gm_'+data['id']).append(
                    '<img data-picid="'+data['id']+'" class="thumbnail_pic" src="'+SERVER_CONTEXT_PATH+'/load/picture/'+data["pictureList"][j]+'" alt="">'
                )
            }
        }
    }

    function submitFn(){
        $('footer').click(function(){
            var dsgId = localStorage.getItem('dsgIds').split(',');
            for(var i = 0; i<dsgId.length; i++){
                if($('.mainPic_'+dsgId[i]).attr('src')=='../img/kong.png'){
                    imageUrl.push('');
                }else if($('.mainPic_'+dsgId[i]).attr('src')){
                    imageUrl.push($('.mainPic_'+dsgId[i]).attr('src').split('load/picture/')[1]);
                }else{
                    imageUrl.push('');
                };
                if($('.textContain_'+dsgId[i]).val()){
                    content.push($('.textContain_'+dsgId[i]).val());
                }else{
                    content.push('');
                };
            };
            for(var i=0; i<dsgId.length; i++){
                designerList.push({
                    'id': _id[i],
                    'dsgId':dsgId[i],
                    'content':content[i],
                    'imageUrl':imageUrl[i],
                    'code':codeId
                })
            };
            console.log(designerList)
            // debugger;
            var data = {
                designerList:designerList
            }
            if(codeId){
                // alert(data)
                post({
                    url:'/customizeOrder/saveDesigner',
                    data:data,
                    success:function(data){
                        console.log(data);
                        localStorage.setItem('cartDesignerIds',data);
                        setTimeout(function() {
                            history.go(-1);
                        }, 300);
                    }
                })
            }else{
                // alert(data)
                post({
                    url:'/customizeCart/saveCartDesigner',
                    data:data,
                    success:function(data){
                        console.log(data);
                        localStorage.setItem('cartDesignerIds',data);
                        setTimeout(function() {
                            history.go(-1);
                        }, 300);
                    }
                })
            }
            
        })
    }

    function operationFn(){
        $('.goBack').click(function(){
            localStorage.setItem('cartId',cartId);
            window.history.go(-1);
        })
        // operat 1
        $('.menuList').delegate('div','click',function(){
            var key = $(this).data('key');
            $(this).addClass('menuList_action').siblings().removeClass('menuList_action');
            $('section').addClass('tab');
            $('.contain_'+key).removeClass('tab');
        });

        // operat 2
        $('article').delegate('.itemHeader_gm','click',function(){
            var key = $(this).data('itemlistid');
            $(this).parent().children().removeClass('itemList_action');
            $(this).addClass('itemList_action')
            console.log($(this).data('itemlistid'))
            $('.itemContain_gm_'+key).parent().find('aside').addClass('tab');
            $('.itemContain_gm_'+key).removeClass('tab');
        });
        $('article').delegate('.itemHeader_st','click',function(){
            var key = $(this).data('itemlistid');
            $(this).parent().children().removeClass('itemList_action');
            $(this).addClass('itemList_action')
            console.log($(this).data('itemlistid'))
            $('.itemContain_st_'+key).parent().find('aside').addClass('tab');
            $('.itemContain_st_'+key).removeClass('tab');
        });
        $('article').delegate('.itemHeader_tw','click',function(){
            var key = $(this).data('itemlistid');
            $(this).parent().children().removeClass('itemList_action');
            $(this).addClass('itemList_action')
            console.log($(this).data('itemlistid'))
            $('.itemContain_tw_'+key).parent().find('aside').addClass('tab');
            $('.itemContain_tw_'+key).removeClass('tab');
        });

        // operat 3
        $('article').delegate('.thumbnail_pic','click',function(){
            var id = $(this).data('picid'),src = $(this).attr('src');
            $(this).parent().children().removeClass('asideImg_action');
            $(this).addClass('asideImg_action');
            $('.mainPic_'+id).attr('src',src)
        });

        // operat 4
        $('article').delegate('.upPic','change',function(){
            console.log($(this))
            var id = $(this).data('uppicid');
            uploadPic($(this), '/upload/picture', '.itemContain_st_'+id, id)
        })
    }

    //照片上传函数
    function uploadPic(dom, url, target,id) {
        var fd = new FormData();
        fd.append("file", $(dom).get(0).files[0]);
        var size = $(dom)[0].files[0].size;
        var type = $(dom)[0].files[0].type;
        if(size<=6*1024*1024){
            if(type == 'image/jpeg' || type == 'image/png'){
                $.ajax({
                    url: SERVER_CONTEXT_PATH + url,
                    type: 'POST',
                    data: fd,
                    processData: false,
                    contentType: false,
                    success: function (data) {
                        console.log(data)
                        console.log(target)
                        $('.mainPic_'+id).attr('src',SERVER_CONTEXT_PATH+'/load/picture/'+data);
                        $(target).append(
                            '<img style="height: 0.68rem;" data-picid="'+id+'" class="thumbnail_pic" src="'+SERVER_CONTEXT_PATH+'/load/picture/'+data+'" alt="">'
                        )
                    },
                    error:function(msg){
                        alert(msg);
                    }
                });
            }else{
                alert('请上传jpg/png格式的照片!');
            }
        }else{
            alert('上传照片不能大于6M!');
        }
    }
})
